#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <fcntl.h>
#include <errno.h>

#include"doorbell.h"

const note Happy[] = {
	{DO,   BEAT}, {RE,   BEAT}, {MI,   BEAT}, {FA, BEAT},
	{SOL,   BEAT}, {LA,   BEAT}, {SI,   BEAT}
};

const note WARNING[] = {
	{DO,   BEAT}, {RE,   BEAT}, {MI,   BEAT}, {FA, BEAT},
	{SOL,   BEAT}, {LA,   BEAT}, {SI,   BEAT},{LA,   BEAT},
	{SOL,   BEAT}, {FA, BEAT},{MI,   BEAT},{RE,   BEAT},{DO,   BEAT}
};

const note HappyNewYear[] = {
	{DO,   BEAT/2}, {DO,   BEAT/2}, {DO,   BEAT}, {SOL/2, BEAT},
	{MI,   BEAT/2}, {MI,   BEAT/2}, {MI,   BEAT}, {DO,    BEAT},
	{DO,   BEAT/2}, {MI,   BEAT/2}, {SOL,  BEAT}, {SOL,    BEAT},
	{FA,   BEAT/2}, {MI,   BEAT/2}, {RE,   BEAT}, {RE,    BEAT},
	{RE,   BEAT/2}, {MI,   BEAT/2}, {FA,   BEAT}, {FA,    BEAT},
	{MI,   BEAT/2}, {RE,   BEAT/2}, {MI,   BEAT}, {DO,    BEAT},
	{DO,   BEAT/2}, {MI,   BEAT/2}, {RE,   BEAT}, {SOL/2, BEAT},
	{SI/2, BEAT/2}, {RE,   BEAT/2}, {DO,   BEAT}, {DO,    BEAT},
};

int doorbell(int sec)
{
	int fd;
	int i = 0;
	int ret;
	unsigned int freq;

	fd = open("/dev/pwm", O_RDWR);
	if (fd < 0) {
		perror("open");
		exit(1);
	}
	//printf("before ioctl1\r\n");

	ret = ioctl(fd,FSPWM_START,0);
	printf("before ioctl 2\r\n");
	ret = ioctl(fd,FSPWM_SET_FREQ,262);
	for(i=0;i<7;i++)
	{
		int j = i%7;
		ret = ioctl(fd,FSPWM_SET_FREQ,Happy[j].pitch);
		usleep(Happy[j].dimation);
	}
	ioctl(fd,FSPWM_STOP,0);
	close(fd);
	return 0;
}

int warning(int sec)
{
	int fd;
	int i = 0;
	int ret;
	unsigned int freq;

	fd = open("/dev/pwm", O_RDWR);
	if (fd < 0) {
		perror("open");
		exit(1);
	}
	//printf("before ioctl1\r\n");

	ret = ioctl(fd,FSPWM_START,0);
	printf("before ioctl 2\r\n");
	ret = ioctl(fd,FSPWM_SET_FREQ,262);
	for(i=0;i<50;i++)
	{
		int j = i%7;
		ret = ioctl(fd,FSPWM_SET_FREQ,WARNING[j].pitch);
		usleep(WARNING[j].dimation);
	}
	ioctl(fd,FSPWM_STOP,0);
	close(fd);
	return 0;
}

